/**
 * 
 */
package wpmp.security.mgr.utils;

import java.util.Iterator;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.internal.CriteriaImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import wpmp.extjs3.data.Page;

/**
 * @author Wayne.Wang<5waynewang@gmail.com>
 * @since 11:42:20 AM Dec 5, 2013
 */
public class PageUtils {

	private static final Logger LOG = LoggerFactory.getLogger(PageUtils.class);

	@SuppressWarnings("unchecked")
	public static Criteria setCriteria(Criteria criteria, Page page, Order... defaultOrders) {
		if (page == null) {
			return HibernateUtils.addOrders(criteria, defaultOrders);
		}
		// hibernate的firstResult的序号从0开始
		criteria.setFirstResult(page.getStart());
		criteria.setMaxResults(page.getLimit());

		if (StringUtils.isBlank(page.getSort()) || StringUtils.isBlank(page.getDir())) {

			if (LOG.isInfoEnabled()) {
				LOG.info("the page's sort or dir is null");
			}

			return HibernateUtils.addOrders(criteria, defaultOrders);
		}

		// org.name
		if (page.getSort().indexOf(".") != -1) {
			String[] sorts = page.getSort().split("\\.");
			Iterator<Criteria> iterator = ((CriteriaImpl) criteria).iterateSubcriteria();
			boolean existAlias = false;
			while (iterator.hasNext()) {
				if (iterator.next().getAlias().equals(sorts[0])) {
					existAlias = true;
					break;
				}
			}
			if (!existAlias) {
				criteria.createAlias(sorts[0], sorts[0]);
			}
		}
		if (Page.ASC.equalsIgnoreCase(page.getDir())) {
			criteria.addOrder(Order.asc(page.getSort()));
		}
		else {
			criteria.addOrder(Order.desc(page.getSort()));
		}
		return criteria;
	}
}
